<template>
  <s-layout :title="brandName" :bg-style="{ backgroundColor: '#f5f5f5' }">
    <view class="page-container">
      <view>
        <!-- 顶部Banner -->
        <view class="header-banner">
          <view class="banner-content">
            <text class="title">自助点餐，到店自提</text>
            <text class="subtitle">提前点餐，出餐后凭取餐码到门店取餐</text>
          </view>
          
          <!-- 功能图标 -->
          <view class="feature-icons">
            <view class="icon-item">
              <view class="icon-wrapper">
                <uni-icons type="shop" size="20" color="#c7000b"></uni-icons>
              </view>
              <text>选择门店</text>
            </view>
            <view class="icon-item">
              <view class="icon-wrapper">
                <uni-icons type="hand-up" size="20" color="#c7000b"></uni-icons>
              </view>
              <text>选择餐品</text>
            </view>
            <view class="icon-item">
              <view class="icon-wrapper">
                <uni-icons type="sound" size="20" color="#c7000b"></uni-icons>
              </view>
              <text>等待出餐</text>
            </view>
            <view class="icon-item">
              <view class="icon-wrapper">
                <uni-icons type="bag" size="20" color="#c7000b"></uni-icons>
              </view>
              <text>到店取餐</text>
            </view>
          </view>
        </view>

        <!-- 搜索栏 -->
        <view class="search-section">
          <view class="city-selector" @click="selectCity">
            <text>{{ currentCityName }}</text>
            <uni-icons type="bottom" size="14" color="#333"></uni-icons>
          </view>
          <view class="search-input">
            <uni-icons type="search" size="18" color="#999"></uni-icons>
            <input v-model="searchKeyword" placeholder="输入地址寻找周边门店" />
          </view>
        </view>
        
        <!-- 定位提示条 -->
        <view v-if="!userLocation" class="location-tip" @click="getUserLocation">
          <uni-icons type="location" size="16" color="#ff6b6b"></uni-icons>
          <text>点击开启定位，显示门店距离</text>
          <uni-icons type="forward" size="14" color="#999"></uni-icons>
        </view>
      </view>

      <!-- 门店列表 -->
      <scroll-view scroll-y class="store-list-container" :style="{ height: listHeight }">
        <view class="store-list">
          <view 
            class="store-item" 
            v-for="store in filteredStores" 
            :key="store.id"
            @click="selectStore(store)"
          >
            <view class="store-info">
              <view class="store-header">
                <text class="store-name">{{ store.name }}</text>
                <view class="store-status" :class="{ 'open': store.status === '营业中' }">
                  <text>{{ store.status }}</text>
                </view>
                <text class="store-distance">{{ store.distance || calcDisplayDistance(store.distanceValue) }}</text>
              </view>
              
              <view class="store-detail">
                <uni-icons type="refreshempty" size="14" color="#999"></uni-icons>
                <text class="detail-text">{{ store.hours }}</text>
              </view>
              
              <view class="store-detail">
                <uni-icons type="location" size="14" color="#999"></uni-icons>
                <text class="detail-text">{{ store.address }}</text>
              </view>
            </view>
            
            <button class="order-btn">去下单</button>
          </view>
          
          <view v-if="filteredStores.length === 0" class="no-result">
            <image class="no-result-icon" src="https://static.thenounproject.com/png/152330-200.png" mode="aspectFit"></image>
            <text class="no-result-text">附近暂无门店</text>
            <text class="no-result-tip">我们正在努力扩展中</text>
          </view>
          <view class="list-footer" v-else>
            <text>没有更多了</text>
          </view>
        </view>
      </scroll-view>
    </view>
    <!-- 底部导航 -->
    <view class="bottom-nav">
      <view class="nav-item active">
        <uni-icons type="shop" size="24" color="#c7000b"></uni-icons>
        <text>点餐首页</text>
      </view>
      <view class="nav-item" @click="goToOrders">
        <uni-icons type="list" size="24" color="#666"></uni-icons>
        <text>我的订单</text>
      </view>
    </view>

    <!-- 城市选择弹窗 -->
    <uni-popup ref="cityPopup" type="bottom">
      <view class="city-popup-content">
        <view class="city-popup-header">
          <text>选择城市</text>
          <view class="close-btn" @click="closeCityPopup">
            <uni-icons type="closeempty" size="24" color="#333"></uni-icons>
          </view>
        </view>
        <view class="current-location-section">
          <view class="section-label">当前定位城市</view>
          <view class="location-city-item" @click="selectCityItem({ id: currentCityId, name: currentCityName })">
            <view class="location-icon">
              <uni-icons type="location" size="20" color="#c7000b"></uni-icons>
            </view>
            <text class="location-city-name">{{ currentCityName }}</text>
          </view>
        </view>
        <view class="city-search-box">
          <uni-icons type="search" size="18" color="#999"></uni-icons>
          <input v-model="citySearchKeyword" placeholder="搜索城市" />
          <view v-if="citySearchKeyword" class="clear-search" @click="citySearchKeyword = ''">
            <uni-icons type="clear" size="16" color="#999"></uni-icons>
          </view>
        </view>
        <view class="section-label section-label-list">全部城市</view>
        <scroll-view scroll-y class="city-list-scroll">
          <view class="city-item" v-for="city in filteredCityList" :key="city.id" @click="selectCityItem(city)">
            <text class="city-name">{{ city.name }}</text>
            <uni-icons v-if="city.id === currentCityId" type="checkmarkempty" size="20" color="#c7000b"></uni-icons>
          </view>
          <view v-if="filteredCityList.length === 0" class="no-city">
            <text>未找到匹配的城市</text>
          </view>
        </scroll-view>
      </view>
    </uni-popup>
  </s-layout>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue';
import sheep from '@/sheep';
import { onLoad, onShow } from '@dcloudio/uni-app';

const cateringStore = sheep.$store('catering');
const searchKeyword = ref('');
const allStores = ref([]);
const brandOt = ref(1);
const brandName = ref('肯德基');
const currentCityId = ref('80');
const currentCityName = ref('洛阳');
const userLocation = ref(null);
const listHeight = ref('0px');
const cityList = ref([]);
const cityPopup = ref(null);
const citySearchKeyword = ref('');

function calcListHeight() {
  try {
    const sys = uni.getSystemInfoSync();
    const windowHeight = sys.windowHeight || 0; // px
    uni.createSelectorQuery()
        .select('.header-banner').boundingClientRect()
        .select('.search-section').boundingClientRect()
        .select('.location-tip').boundingClientRect()
        .select('.bottom-nav').boundingClientRect()
        .exec(rects => {
          const headerRect = rects && rects[0] ? rects[0] : { height: 0 };
          const searchRect = rects && rects[1] ? rects[1] : { height: 0 };
          const locationTipRect = rects && rects[2] ? rects[2] : { height: 0 };
          const bottomRect = rects && rects[3] ? rects[3] : { height: 0 };
          let h = windowHeight - headerRect.height - searchRect.height - locationTipRect.height - bottomRect.height;
          if (h < 120) h = 120; // 最小高度兜底，防止为负
          listHeight.value = `${Math.round(h)}px`;
          console.log('【列表高度】计算结果:', { 
            windowHeight, 
            header: headerRect.height, 
            search: searchRect.height, 
            locationTip: locationTipRect.height,
            bottom: bottomRect.height, 
            listHeight: listHeight.value 
          });
        });
  } catch (e) {
    console.error('【列表高度】计算失败:', e);
  }
}

// 顶部安全区样式
const statusBarHeight = uni.getSystemInfoSync().statusBarHeight || 0;
const navBarStyle = computed(() => ({
  paddingTop: `${statusBarHeight}px`,
  height: `${statusBarHeight + 44}px`
}));

onLoad((options) => {
  if (options.ot) {
    brandOt.value = parseInt(options.ot);
  }
  if (options.cateringName) {
    brandName.value = options.cateringName;
  }
  if (options.cityId) {
    currentCityId.value = options.cityId;
  }
  if (options.cityName) {
    currentCityName.value = options.cityName;
  }
  
  console.log('门店列表页参数:', { brandName: brandName.value, cityName: currentCityName.value });
});

onMounted(() => {
  nextTick(() => {
    calcListHeight();
  });
  getUserLocation();
  loadStoreList();
});

onShow(() => {
  // 每次页面显示时清空搜索框
  searchKeyword.value = '';
  citySearchKeyword.value = '';
});

// 监听定位状态变化，重新计算列表高度（定位提示条会显示/隐藏）
watch(userLocation, () => {
  nextTick(() => {
    calcListHeight();
  });
});

function goBack() {
  if (getCurrentPages && getCurrentPages().length > 1) {
    uni.navigateBack({ delta: 1 });
  } else {
    sheep.$router.go('/pages/catering/store-detail', { ot: brandOt.value, cateringName: brandName.value, cityId: currentCityId.value, cityName: currentCityName.value });
  }
}

// 获取用户位置
function getUserLocation() {
  // #ifdef MP-WEIXIN
  // 小程序端：先检查授权状态
  uni.getSetting({
    success: (res) => {
      console.log('【定位权限】授权状态:', res.authSetting);
      if (res.authSetting['scope.userLocation'] === false) {
        // 用户已拒绝授权，引导用户打开设置
        console.warn('【定位权限】用户已拒绝授权');
        uni.showModal({
          title: '需要位置权限',
          content: '为了显示附近门店距离，需要获取您的位置信息',
          confirmText: '去设置',
          success: (modalRes) => {
            if (modalRes.confirm) {
              uni.openSetting({
                success: (settingRes) => {
                  console.log('【定位权限】设置返回:', settingRes.authSetting);
                  if (settingRes.authSetting['scope.userLocation']) {
                    // 用户已授权，重新获取位置
                    getLocationData();
                  } else {
                    calculateDistances();
                  }
                }
              });
            } else {
              calculateDistances();
            }
          }
        });
      } else {
        // 未授权或已授权，直接获取位置
        getLocationData();
      }
    },
    fail: () => {
      console.error('【定位权限】获取授权状态失败');
      getLocationData();
    }
  });
  // #endif
  
  // #ifndef MP-WEIXIN
  // 非小程序端：直接获取位置
  getLocationData();
  // #endif
}

// 实际获取位置数据
function getLocationData() {
  console.log('【定位】开始获取位置...');
  uni.getLocation({
    type: 'gcj02',
    isHighAccuracy: true,
    success: (res) => {
      userLocation.value = {
        latitude: res.latitude,
        longitude: res.longitude
      };
      console.log('✅ 【定位成功】用户位置:', userLocation.value);
      // 重新计算距离并排序
      calculateDistances();
    },
    fail: (err) => {
      console.error('❌ 【定位失败】错误信息:', err);
      console.error('❌ 【定位失败】错误码:', err.errCode);
      console.error('❌ 【定位失败】错误消息:', err.errMsg);
      
      // 定位失败也继续展示列表
      calculateDistances();
      
      // 根据错误类型显示不同提示
      if (err.errMsg && err.errMsg.indexOf('auth deny') > -1) {
        console.warn('【定位失败】用户拒绝授权');
        // 用户拒绝了授权，不显示toast，避免打扰用户
      } else {
        uni.showToast({
          title: '定位失败，无法显示距离',
          icon: 'none',
          duration: 2000
        });
      }
    }
  });
}

// 加载门店列表
async function loadStoreList() {
  uni.showLoading({ title: '加载中...' });
  try {
    const params = {
      cityId: currentCityId.value || 80,
      ot: brandOt.value
    };
    
    const res = await sheep.$api.catering.getStoreList(params);
    uni.hideLoading();
    
    console.log('门店列表API原始返回:', res);

    if (res.code === 200 && res.data) {
      console.log('【门店列表】API返回的原始数据:', res.data);
      
      allStores.value = Array.isArray(res.data) ? res.data.map((shop, idx) => {
        const storeData = {
          id: shop.id || shop.shopId,
          shopId: shop.shopId || shop.id,
          name: shop.name || shop.shopName,
          address: shop.address || shop.shopAddress,
          status: shop.status || '营业中',
          distance: shop.distance || '',
          distanceValue: 0, // 用于排序的实际距离值
          hours: shop.hours || shop.businessHours || '08:00 - 21:00',
          latitude: parseFloat(shop.latitude || shop.lat || 0),
          longitude: parseFloat(shop.longitude || shop.lon || shop.lng || 0)
        };
        
        console.log(`【门店列表】门店[${idx}] ${storeData.name}`);
        console.log(`【门店列表】  - 原始坐标: lat=${shop.latitude}, lon=${shop.longitude}`);
        console.log(`【门店列表】  - 解析坐标: lat=${storeData.latitude}, lon=${storeData.longitude}`);
        
        return storeData;
      }) : [];
      
      console.log('【门店列表】格式化后的门店数据:', allStores.value.length, '个');
      // 计算距离并排序（即使用户位置不可用也调用以确保 distanceValue 存在）
      calculateDistances();
    } else {
      allStores.value = [];
      uni.showToast({
        title: '加载门店失败',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('加载门店列表失败:', error);
    uni.showToast({
      title: '加载失败，请重试',
      icon: 'none'
    });
  }
}

// 计算距离（使用Haversine公式）
function calculateDistance(lat1, lon1, lat2, lon2) {
  const R = 6371; // 地球半径（公里）
  const dLat = (lat2 - lat1) * Math.PI / 180;
  const dLon = (lon2 - lon1) * Math.PI / 180;
  const a = 
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
    Math.sin(dLon / 2) * Math.sin(dLon / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  const distance = R * c;
  console.log(`计算距离: (${lat1},${lon1}) -> (${lat2},${lon2}) = ${distance}km`);
  return distance;
}

function calcDisplayDistance(distanceKm) {
  if (!distanceKm || distanceKm <= 0) return '';
  return distanceKm < 1 ? `${Math.round(distanceKm * 1000)}m` : `${distanceKm.toFixed(1)}km`;
}

// 计算所有门店距离并排序
function calculateDistances() {
  const hasUserLoc = !!userLocation.value;
  
  console.log('【距离计算】开始计算所有门店距离');
  console.log('【距离计算】是否有用户位置:', hasUserLoc);
  if (hasUserLoc) {
    console.log('【距离计算】用户位置:', userLocation.value);
  }

  allStores.value = allStores.value.map((store, index) => {
    let distance = 0;
    const latOk = Number.isFinite(store.latitude) && Math.abs(store.latitude) > 0.01;
    const lonOk = Number.isFinite(store.longitude) && Math.abs(store.longitude) > 0.01;
    
    console.log(`【距离计算】门店[${index}] ${store.name}`);
    console.log(`【距离计算】  - 坐标: (${store.latitude}, ${store.longitude})`);
    console.log(`【距离计算】  - 坐标有效: lat=${latOk}, lon=${lonOk}`);
    
    if (hasUserLoc && latOk && lonOk) {
      distance = calculateDistance(
          Number(userLocation.value.latitude),
          Number(userLocation.value.longitude),
          Number(store.latitude),
          Number(store.longitude)
      );
      console.log(`【距离计算】  - 计算距离: ${distance}km`);
    } else {
      console.log(`【距离计算】  - 无法计算距离（定位=${hasUserLoc}, 坐标有效=${latOk && lonOk}）`);
    }
    
    const displayDistance = distance > 0 ? calcDisplayDistance(distance) : (store.distance || '');
    console.log(`【距离计算】  - 显示距离: ${displayDistance}`);
    
    return {
      ...store,
      distanceValue: distance,
      distance: displayDistance
    };
  }).sort((a, b) => {
    // 有距离的优先；都没有时保持原序
    if (a.distanceValue === 0 && b.distanceValue === 0) return 0;
    if (a.distanceValue === 0) return 1;
    if (b.distanceValue === 0) return -1;
    return a.distanceValue - b.distanceValue;
  });

  console.log('【距离计算】完成，门店数量:', allStores.value.length);
  console.log('【距离计算】排序后的门店:', allStores.value.map(s => ({
    name: s.name,
    distance: s.distance,
    distanceValue: s.distanceValue
  })));
}

// 搜索过滤
const filteredStores = computed(() => {
  const list = !searchKeyword.value
    ? allStores.value
    : allStores.value.filter(store => 
        (store.name && store.name.includes(searchKeyword.value)) || 
        (store.address && store.address.includes(searchKeyword.value))
      );
  // 保证筛选后也为按距离排序
  return [...list].sort((a, b) => {
    if (a.distanceValue === 0 && b.distanceValue === 0) return 0;
    if (a.distanceValue === 0) return 1;
    if (b.distanceValue === 0) return -1;
    return a.distanceValue - b.distanceValue;
  });
});

// 城市搜索过滤
const filteredCityList = computed(() => {
  if (!citySearchKeyword.value) {
    return cityList.value;
  }
  return cityList.value.filter(city => 
    city.name && city.name.includes(citySearchKeyword.value)
  );
});

// 选择城市
async function selectCity() {
  // 如果城市列表为空，先加载
  if (cityList.value.length === 0) {
    uni.showLoading({ title: '加载城市...' });
    try {
      const res = await sheep.$api.catering.getCityList();
      uni.hideLoading();
      if ((res.code === 0 || res.code === 200) && res.data) {
        cityList.value = Array.isArray(res.data) ? res.data.map(c => ({
          id: String(c.id || c.cityId),
          name: c.name || c.cityName
        })) : [];
      } else {
        uni.showToast({ title: '加载城市失败', icon: 'none' });
        return;
      }
    } catch (error) {
      uni.hideLoading();
      console.error('加载城市列表失败:', error);
      uni.showToast({ title: '加载城市失败', icon: 'none' });
      return;
    }
  }
  cityPopup.value.open();
}

function closeCityPopup() {
  cityPopup.value.close();
  // 关闭弹窗时清空搜索关键词
  citySearchKeyword.value = '';
}

function selectCityItem(city) {
  currentCityId.value = city.id;
  currentCityName.value = city.name;
  cityPopup.value.close();
  uni.showToast({ title: `切换到${city.name}`, icon: 'success', duration: 1500 });
  // 重新加载门店列表
  loadStoreList();
}

// 选择门店
function selectStore(store) {
  // 确保 store 对象包含 ot 字段
  const storeWithOt = {
    ...store,
    ot: brandOt.value, // 添加品牌类型
    orderType: brandOt.value, // 备用字段
    brandName: brandName.value // 品牌名称
  };
  
  console.log('【选择门店】原始门店数据:', store);
  console.log('【选择门店】设置门店信息，ot:', brandOt.value, '品牌:', brandName.value, '门店ID:', store.id || store.shopId);
  cateringStore.setStore(storeWithOt);
  console.log('【选择门店】存储后的storeInfo:', cateringStore.storeInfo);
  sheep.$router.go('/pages/catering/menu');
}

// 跳转到订单列表
function goToOrders() {
  // 跳到当前品牌的点餐订单列表
  // 如果已选择门店，则传递门店ID筛选；否则不传shopId，显示该餐厅所有门店的订单
  console.log('【门店列表】当前storeInfo:', cateringStore.storeInfo);
  const shopId = (cateringStore.storeInfo?.shopId || cateringStore.storeInfo?.id) || '';
  console.log('【门店列表】跳转我的订单，品牌:', brandName.value, 'ot:', brandOt.value, '门店ID:', shopId || '全部门店');
  
  const params = {
    ot: brandOt.value,
    cateringName: brandName.value
  };
  
  // 只有当shopId有值时才传递（避免空字符串被忽略）
  if (shopId) {
    params.shopId = shopId;
  }
  
  sheep.$router.go('/pages/catering/order-list', params);
}
</script>

<style lang="scss" scoped>
:deep(.s-layout-content) {
  height: 100%;
  overflow: hidden; // 禁止外层滚动
}

.page-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden; // 禁止外层滚动
}

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 88rpx; // 实际高度由内联样式重写
  display: flex;
  align-items: center;
  padding: 0 20rpx;
  background: rgba(255,255,255,0.9);
  z-index: 1000;
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.header-banner {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
  padding: 30rpx;
  color: #fff;
  
  .banner-content {
    .title {
      display: block;
      font-size: 36rpx;
      font-weight: bold;
      margin-bottom: 10rpx;
    }
    
    .subtitle {
      display: block;
      font-size: 24rpx;
      opacity: 0.9;
    }
  }
  
  .feature-icons {
    display: flex;
    justify-content: space-around;
    margin-top: 30rpx;
    
    .icon-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      font-size: 22rpx;
      
      .icon-wrapper {
        width: 60rpx;
        height: 60rpx;
        background-color: rgba(255, 255, 255, 0.9);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 8rpx;
      }
    }
  }
}

/* 用内联样式的高度来设置 CSS 变量以便计算列表可视高度（在容器上由内联生效）*/
:host, .store-select-container {
  --nav-safe-height: 88rpx; /* 兜底值，内联样式会覆盖为 statusBarHeight+44 */
}

.search-section {
  background-color: #fff;
  padding: 20rpx 30rpx;
  display: flex;
  align-items: center;
  gap: 20rpx;
  
  .city-selector {
    display: flex;
    align-items: center;
    gap: 4rpx;
    font-size: 28rpx;
    color: #333;
    white-space: nowrap;
  }
  
  .search-input {
    flex: 1;
    display: flex;
    align-items: center;
    background-color: #f5f5f5;
    border-radius: 30rpx;
    padding: 12rpx 24rpx;
    gap: 10rpx;
    
    input {
      flex: 1;
      font-size: 26rpx;
    }
  }
}

.location-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
  padding: 20rpx 30rpx;
  background: linear-gradient(90deg, #fff5f5 0%, #fff 100%);
  border-bottom: 1rpx solid #ffe0e0;
  font-size: 24rpx;
  color: #666;
  
  text {
    color: #ff6b6b;
  }
  
  &:active {
    opacity: 0.8;
  }
}

.store-list-container {
  overflow: auto; // 自身滚动
  min-height: 0;
}

.store-list {
  height: 100%;
  padding: 0 30rpx;
  padding-bottom: 120rpx;
}

.store-item {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-top: 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  
  .store-info {
    flex: 1;
    
    .store-header {
      display: flex;
      align-items: center;
      margin-bottom: 12rpx;
      
      .store-name {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-right: 10rpx;
      }
      
      .store-status {
        padding: 4rpx 12rpx;
        border-radius: 6rpx;
        font-size: 20rpx;
        background-color: #e0e0e0;
        color: #666;
        margin-right: 10rpx;
        
        &.open {
          background-color: #ffc107;
          color: #fff;
        }
      }
      
      .store-distance {
        font-size: 24rpx;
        color: #999;
        margin-left: auto;
      }
    }
    
    .store-detail {
      display: flex;
      align-items: center;
      gap: 8rpx;
      margin-top: 8rpx;
      
      .detail-text {
        font-size: 24rpx;
        color: #999;
      }
    }
  }
  
  .order-btn {
    background-color: #c7000b;
    color: #fff;
    font-size: 24rpx;
    border-radius: 30rpx;
    border: none;
    margin-left: 20rpx;
  }
}

.list-footer {
  text-align: center;
  padding: 20rpx 0 80rpx 0;
  color: #999;
  font-size: 24rpx;
}
.no-result {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-top: 100rpx;
  
  .no-result-icon {
    width: 120rpx;
    height: 120rpx;
    opacity: 0.4;
    margin-bottom: 20rpx;
  }

  .no-result-text {
    font-size: 28rpx;
    color: #999;
  }

  .no-result-tip {
    font-size: 24rpx;
    color: #ccc;
    margin-top: 10rpx;
  }
}

.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  background-color: #fff;
  border-top: 1rpx solid #f0f0f0;
  padding: 10rpx 0;
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  z-index: 100;
  
  .nav-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 20rpx;
    color: #666;
    
    &.active {
      color: #c7000b;
    }
  }
}

.city-popup-content {
  background-color: #fff;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  max-height: 80vh;
  display: flex;
  flex-direction: column;

  .city-popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1rpx solid #f0f0f0;
    font-size: 32rpx;
    font-weight: bold;

    .close-btn {
      display: flex;
      align-items: center;
    }
  }

  .current-location-section {
    padding: 0 30rpx 20rpx 30rpx;
    border-bottom: 1rpx solid #f0f0f0;

    .section-label {
      font-size: 24rpx;
      color: #999;
      margin-bottom: 15rpx;
    }

    .location-city-item {
      display: flex;
      align-items: center;
      padding: 20rpx 30rpx;
      background-color: #fff5f5;
      border-radius: 12rpx;
      border: 1rpx solid #c7000b;
      gap: 10rpx;

      .location-icon {
        display: flex;
        align-items: center;
      }

      .location-city-name {
        font-size: 28rpx;
        color: #c7000b;
        font-weight: bold;
      }

      &:active {
        opacity: 0.8;
      }
    }
  }

  .city-search-box {
    display: flex;
    align-items: center;
    padding: 20rpx 30rpx;
    background-color: #f5f5f5;
    margin: 20rpx 30rpx 20rpx 30rpx;
    border-radius: 30rpx;
    gap: 10rpx;

    input {
      flex: 1;
      font-size: 26rpx;
    }

    .clear-search {
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .section-label-list {
    font-size: 24rpx;
    color: #999;
    padding: 10rpx 30rpx;
    background-color: #fafafa;
  }

  .city-list-scroll {
    height: 35vh;
    padding: 0rpx 0;
  }

  .city-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 40rpx;
    border-bottom: 1rpx solid #f5f5f5;

    .city-name {
      font-size: 28rpx;
      color: #333;
    }

    &:active {
      background-color: #f5f5f5;
    }
  }

  .no-city {
    text-align: center;
    padding: 80rpx 0;
    color: #999;
    font-size: 28rpx;
  }
}
</style>

